<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>基地管理</el-breadcrumb-item>
      <el-breadcrumb-item>员工管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加区域 -->
      <el-row
        class="globalHeader"
        style="margin-bottom: 20px; padding-bottom: 45px"
      >
        <el-col :span="4">
          <i class="el-icon-user"></i>
          <span>员工管理</span>
        </el-col>
        <el-col style="width: 100px; float: right">
          <el-button type="primary" @click="addDialogVisible = true"
            >邀请员工</el-button
          >
        </el-col>
      </el-row>

      <!-- 员工列表区域 -->
      <el-table :data="personInfoList" border stripe>
        <!-- :data: 放入数据源 -->
        <!-- border： 加入边框线 -->
        <!-- type="index"： 索引列 -->
        >
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="workType" label="角色"></el-table-column>
        <el-table-column prop="mobile" label="联系电话"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditDialog(scope.row.userId)"
            ></el-button>
            <!-- 删除按钮 -->
            <!-- type="danger": 红色警告按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="removePersonInfoById(scope.row.userId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[4, 6, 8, 10]"
        :page-size="pageInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 邀请员工的对话框 -->
    <el-dialog
      title="邀请员工"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
    <el-form :model="searchForm" :rules="searchFormRules" ref="searchFormRef" label-width="100px">
      <el-form-item label="搜索员工" prop="name" class="inviteMember">
        <el-input placeholder="请输入要邀请的员工姓名或员工的用户ID" v-model="searchForm.name" class="input-with-select">
        <el-button slot="append" icon="el-icon-search" @click="searchInviteMember"></el-button>
        </el-input>
      </el-form-item>
    </el-form>
      <el-table
      :data="inviteForm"
      height="250"
      style="width: 100%"
      v-loading="loading"
      >
      <el-table-column
        prop="name"
        label="姓名"
        width="80">
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        width="80">
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="手机号码"
        width="180">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        width="180">
      </el-table-column>
      <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="primary"
          @click="inviteWorker(scope.row)">邀请</el-button>
      </template>
    </el-table-column>
    </el-table>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 修改人员的对话框 -->
    <el-dialog
      title="修改人员"
      :visible.sync="editDialogVisible"
      width="23%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <!-- ref:引用，指向本身，用于使用自身的方法 -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input v-model="editForm.sex" placeholder="请选择" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="baseIdentity">
          <el-select v-model="editForm.baseIdentity" placeholder="请选择角色">
            <el-option label="经理" value="3"></el-option>
            <el-option label="员工" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input v-model="editForm.mobile" disabled></el-input>
        </el-form-item>
      </el-form>

      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editPersonInfo" :disabled="editForm.baseIdentity == '老板' || editForm.baseIdentity == '经理' || editForm.baseIdentity == '员工'">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义规则：（rule：规则， value：待校验的值，cb:回调函数）
    // 自定义验证手机号规则，后在addeFormRules中使用
    var checkMobile = (rule, value, cb) => {
      // 先定义一个验证手机号的正则表达式
      const regMobile = /^1[34578]\d{9}$/
      // 合法： regMobile.test(value)进过测试后放回的值
      if (regMobile.test(value)) {
        return cb()
      }
      // 不合法
      cb(new Error('请输入合法的手机号'))
    }

    return {
      token: window.localStorage.getItem('token'),
      // 用于控制分页的当前页码和条数
      pageInfo: {
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 4,
      },

      baseId: this.$store.state.baseId,

      // 用于存放人员信息
      personInfoList: [],

      // 总条数
      total: 0,

      // 控制添加人员对话框的显示与隐藏
      addDialogVisible: false,

      // 控制修改人员对话框的显示和隐藏
      editDialogVisible: false,

      // 加载表格
      loading: false,
      // 搜索要邀请的员工
      searchForm: { name: '' , loginId: ''},
      // 搜索员工的验证规则对象
      searchFormRules: {
        name: { required: true, message: '请输入姓名', trigger: 'blur' },
      },
      // 可邀请的员工名单
      inviteForm: [],
      // 添加表单的验证规则对象
      addeFormRules: {
        personName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '姓名的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        sex: [{ required: true, message: '请输入性别', trigger: 'blur' }],
        politicalStatus: [
          { required: true, message: '请输入政治面貌', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: checkMobile, teigger: 'blur' },
        ],
        workType: [
          { required: true, message: '请输入工种类别', trigger: 'blur' },
        ],
      },

      // 保存性别选项
      options: [
        {
          value: '男',
          label: '男',
        },
        {
          value: '女',
          label: '女',
        },
      ],
      // 保存政治面貌
      options2: [
        {
          value: '党员',
          label: '党员',
        },
        {
          value: '共青团员',
          label: '共青团员',
        },
        {
          value: '群众',
          label: '群众',
        },
      ],

      // 查询到的人员信息对象
      editForm: {},

      // 修改表单的验证规则对象
      editFormRules: {
        workType: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.getStaffInfoList()
  },
  methods: {
    // 获取基地员工信息
    async getStaffInfoList() {
      const { data: res } = await this.$http.get(
        `${this.$limit}/user/getBaseMember/${this.pageInfo.pagenum}/${this.pageInfo.pagesize}`,
        {
          headers: {
            Authorization: this.token
          }
        }
      )
      // console.log(res)
      this.personInfoList = res.data.rows
      this.total = res.data.total
      this.personInfoList.forEach(e => {
        if(e.baseIdentity == 2) {
          e.workType = '老板'
        }else if(e.baseIdentity == 3) {
          e.workType = '经理'
        } else if(e.baseIdentity == 4) {
          e.workType = '员工'
        }
      });
    },

    // 监听pagesize(每页显示条数)改变事件
    handleSizeChange(newSize) {
      this.pageInfo.pagesize = newSize
      this.getStaffInfoList()
    },

    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.pageInfo.pagenum = newPage
      this.getStaffInfoList()
    },

    // 搜索要邀请的员工
    async searchInviteMember() {
      this.loading = true
      if(this.searchForm.name == '') {
        return this.$message.error('请输入员工姓名或用户名！')
      }
      // console.log(this.searchForm)
      this.searchForm.loginId = ''
      // 先判断是否可以用姓名搜索到员工
      const { data: res } = await this.$http.post(`${this.$limit}/user/getNoBaseUser`, this.searchForm, {
        headers: {
          Authorization: this.token
        }
      })
      this.inviteForm = res.data

      // 如果姓名搜索不到员工，尝试用ID进行搜索
      if(this.inviteForm.length == 0) {
        this.searchForm.loginId = this.searchForm.name
        this.searchForm.name = ''
        const { data: res } = await this.$http.post(`${this.$limit}/user/getNoBaseUser`, this.searchForm, {
          headers: {
            Authorization: this.token
          }
        })
        this.inviteForm = res.data
      }
      // console.log(res)
      if(this.inviteForm.length === 0) {
        this.loading = false
        return this.$message.error('查无此员工！')
      } else {
        this.loading = false
        return this.$message.success('查询到' + this.inviteForm.length + '条结果')
      }
    },

    // 邀请员工
    async inviteWorker(user) {
      const { data: res } = await this.$http.get(`${this.$limit}/user/invite/${user.userId}`,
        {
          headers: {
            Authorization: this.token
          }
        })
      this.$message.info(res.message)
    },

    // 监听添加人员对话框的关闭事件,关闭时对表单进行重置
    addDialogClosed() {
      // 表单方法：resetFields：对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      // this.$refs.addeFormRef.resetFields()
      this.addDialogVisible = false
    },

    // 监听修改人员对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    // 点击按钮，添加新人员
    addPersonInfo() {
      // 先进行表单的预校验
      this.$refs.addeFormRef.validate(async (valid) => {
        // 表单自身方法：validate：进行表单预验证，放回验证结果，用valid接收
        if (!valid) return false
        // 成功后，可以发起添加用户的网络请求
        this.addeForm.baseId = this.baseId
        const { data: res } = await this.$http.post(
          '/personinfo',
          this.addeForm
        )
        // console.log(res)
        if (res.code !== 20000) {
          return this.$message.error('人员名称或电话号码重复！！请重新输入')
        }
        this.$message.success('添加人员成功!!')
        // 隐藏添加的对话框
        this.addDialogVisible = false
        // 成功后新增，需要刷新列表
        this.getPersonInfoList()
      })
    },

    // 展示修改的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`${this.$limit}/user/${id}`, {
        headers: {
          Authorization: this.token
        }
      })
      if (res.code !== 20000) {
        return this.$message.error('当前用户无修改权限！！')
      }
      this.editForm = res.data
      if(this.editForm.baseIdentity == 2) {
        this.editForm.baseIdentity = '老板'
      }else if(this.editForm.baseIdentity == 3) {
        this.editForm.baseIdentity = '经理'
      } else if(this.editForm.baseIdentity == 4) {
        this.editForm.baseIdentity = '员工'
      }
      console.log(this.editForm)
      this.editDialogVisible = true
    },

    // 修改人员信息并提交
    editPersonInfo() {
      // 先进行表单的预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return false
        // 正确，则会发起修改用户信息的请求
        const { data: res } = await this.$http.put(
          `${this.$limit}/user/update/${this.editForm.userId}/${this.editForm.baseIdentity}`, {},
          {
            headers: {
              Authorization: this.token
            }
          })
        console.log(res)
        if (res.code !== 20000) {
          return this.$message.error('更新人员信息失败！！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新人员列表
        this.getStaffInfoList()
        // 提示修改成功
        this.$message.success('更新人员信息成功！！')
      })
    },

    // 根据人员id删除对应的人员信息
    async removePersonInfoById(id) {
      // 弹框询问用户是否删除数据
      // 前提：在elementUI中挂载confirm
      // （提示消息，标题文本，｛确认按钮的文本，取消按钮的文本，提示的类型｝）
      const confirmResult = await this.$confirm(
        '此操作将永久删除该人员, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
        // .catch 用于捕获错误返回给confirmResult
      ).catch((err) => {
        return err
      })
      // 如果人员确认删除，则返回值为字符串 confirm
      // 如果人员取消了删除， 则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        // this.$message.info: 灰色提示框
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.put(`${this.$limit}/user/sack/${id}`,{},
      {
        headers: {
          Authorization: this.token
        }
      })
      console.log(res)
      this.$message.success('删除人员成功！！')
      this.getStaffInfoList()
    },
  },
}
</script>

<style lang="less" scoped></style>
